import app from '../App.vue';
const http = (options) => {
    return new Promise((resolve, reject) => {
        try{
            uni.request({
                url: (options.baseURL || app.globalData.baseURL) + options.url,
                method: options.method || 'POST',
                data: options.data,
				timeout: 10000,
                header: {
                    'token': '',
                    'Content-Type': options.header == 'form' ? 'application/x-www-form-urlencoded' : 'application/json',
					'time': Date.parse(new Date())
                },
                success: res => {
					if(res.statusCode===200){
						if(res.data.code===0){
							resolve(res.data.data);
						}else if(res.data.code===401){
							reject(res.data);
						}else{
							reject(res.data.data);
							let msg=JSON.parse(res.data.message);
							setTimeout(function() {
								uni.showToast({
									title: res.data.message?(uni.getLocale()=='vi'?msg.via:uni.getLocale()=='zh-Hans'?msg.zh:msg.en): (uni.getLocale()=='vi'?'Server không trả về':uni.getLocale()=='zh-Hans'?'服务器无返回':'The server did not return anything'),
									icon:'none',
									duration: 2000
								})
								setTimeout(function() {
									uni.hideToast();
								}, 2000);
							}, 100);
						}
					}else{
						let msg=JSON.parse(res.data.message);
						setTimeout(function() {
							uni.showToast({
								title: res.data.message?(uni.getLocale()=='vi'?msg.via:uni.getLocale()=='zh-Hans'?msg.zh:msg.en): (uni.getLocale()=='vi'?'Server không trả về':uni.getLocale()=='zh-Hans'?'服务器无返回':'The server did not return anything'),
								icon:'none',
								duration: 2000
							})
							setTimeout(function() {
								uni.hideToast();
							}, 2000);
						}, 100);
					}
                },
                fail: (err) => {
                    reject(err.data);
                    uni.showToast({
                        title: (uni.getLocale()=='vi'?'Server ngoại lệ':uni.getLocale()=='zh-Hans'?'服务器异常':'Server exception'),
                        icon: 'none'
                    })
                },
                complete: () => {
					uni.stopPullDownRefresh();
                }
            });
        }catch(e){
            uni.showToast({
                title: (uni.getLocale()=='vi'?'Vui lòng kiểm tra kết nối mạng':uni.getLocale()=='zh-Hans'?'请检查网络连接':'Please check the network connection'),
                icon: 'none'
            })
        }
        
    })
}

export default http